﻿using System;
using System.Collections.Generic;
using System.Globalization;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.EntityModel;
using MonkeyWarranty.Web.Common;

namespace MonkeyWarranty.Web.WarrantyTickets
{
    public partial class New : System.Web.UI.Page
    {
        #region Properties

        private WarrantyTicketBiz _warrantyTicketBiz;

        private WarrantyTicketBiz WarrantyTicketManager
        {
            get { return _warrantyTicketBiz ?? (_warrantyTicketBiz = new WarrantyTicketBiz()); }
        }

        private static CustomerBiz _customerBiz;
        private static CustomerBiz CustomerManager
        {
            get { return _customerBiz ?? (_customerBiz = new CustomerBiz()); }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //txtCode.Text = string.Format("{0:00000}", WarrantyTicketManager.GetNextCode());
                txtCode.Text = string.Format("{0:00000}", WarrantyCommon.WarrantyTicketNextCode);
                txtReceivedDate.Text = string.Format("{0:dd/MM/yyyy}", DateTime.Now);
                txtDeliveryDate.Text = string.Format("{0:dd/MM/yyyy}", DateTime.Now.AddDays(7));

                // load employees
                var employees = WarrantyTicketManager.GetEmployees();
                ddlEmployees.DataSource = employees;
                ddlEmployees.DataValueField = "Id";
                ddlEmployees.DataTextField = "Name";
                ddlEmployees.DataBind();

                var fromEmployees = new List<Employee> { new Employee { Id = 0, Name = string.Empty } };
                fromEmployees.AddRange(employees);
                ddlFromEmployees.DataSource = fromEmployees;
                ddlFromEmployees.DataValueField = "Id";
                ddlFromEmployees.DataTextField = "Name";
                ddlFromEmployees.DataBind();

                // load dealers
                var dealers = WarrantyTicketManager.GetDealers();
                dealers.Insert(0, new Dealer { Id = 0, Name = string.Empty });
                ddlDealers.DataSource = dealers;
                ddlDealers.DataValueField = "Id";
                ddlDealers.DataTextField = "Name";
                ddlDealers.DataBind();

                // load customers
                var groups = CustomerManager.GetAllCustomerGroups();
                groups.Insert(0, new CustomerGroup { Id = 0, Name = Resources.GlobalStrings.AllGroups });
                ddlCustomerGroups.DataValueField = "Id";
                ddlCustomerGroups.DataTextField = "Name";
                ddlCustomerGroups.DataSource = groups;
                ddlCustomerGroups.DataBind();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblErrorMessage.Text = string.Empty;

            // validate inputs
            var code = txtCode.Text.Trim();
            if (code.Length == 0)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.CodeIsRequired;
                return;
            }
            DateTime createdDate;
            if (!DateTime.TryParseExact(txtReceivedDate.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDate))
            {
                lblErrorMessage.Text = Resources.GlobalStrings.InvalidDate;
                return;
            }
            DateTime wishDate;
            if (!DateTime.TryParseExact(txtDeliveryDate.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out wishDate))
            {
                lblErrorMessage.Text = Resources.GlobalStrings.InvalidDate;
                return;
            }

            if (ddlEmployees.SelectedIndex < 0)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.ReceivedEmployeeRequired;
                return;
            }
            var ticketContent = txtContent.Text.Trim();
            if (ticketContent.Length == 0)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.TicketContentRequired;
                return;
            }

            Customer customer;
            if (rbtNewCustomer.Checked)
            {
                var name = txtName.Text.Trim();
                if (name.Length == 0)
                {
                    lblErrorMessage.Text = Resources.GlobalStrings.NameIsRequired;
                    return;
                }
                customer = new Customer
                {
                    Name = name,
                    Address = txtAddress.Text.Trim(),
                    Email = txtEmail.Text.Trim(),
                    Phone = txtPhone.Text.Trim()
                };
            }
            else
            {
                int customerId;
                if (!int.TryParse(hidCustomerId.Value, out customerId))
                {
                    lblErrorMessage.Text = Resources.GlobalStrings.CustomerRequired;
                    return;
                }
                if (customerId <= 0)
                {
                    lblErrorMessage.Text = Resources.GlobalStrings.CustomerRequired;
                    return;
                }
                customer = new Customer { Id = customerId };
            }

            // call create instant ticket biz
            var warrTicket = new WarrantyTicket
            {
                Code = code,
                CreatedDate = createdDate,
                CreatedEmployeeId = int.Parse(ddlEmployees.SelectedValue),
                TicketContent = ticketContent,
                StatusId = 1, // waiting for warranty
                DeliveryDate = wishDate,
                ReceivedFrom = int.Parse(ddlReceivedFrom.SelectedValue)
            };

            switch (ddlReceivedFrom.SelectedValue)
            {
                case "2":
                    warrTicket.EmployeeIdFrom = int.Parse(ddlFromEmployees.SelectedValue);
                    break;
                case "3":
                    warrTicket.DealerIdFrom = int.Parse(ddlDealers.SelectedValue);
                    break;
            }
            
            WarrantyTicketManager.CreateTicket(warrTicket, customer);
            // check result

            // go to Edit page
            Response.Redirect("Edit.aspx?id=" + warrTicket.Id);
        }

        #endregion
    }
}